import dayjs from 'dayjs';

/**
 * 格式化日期为YYYY-MM-DD格式
 * @param date 日期对象或日期字符串
 * @returns 格式化后的日期字符串
 */
export const formatDate = (date: Date | string): string => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD');
};

/**
 * 计算两个日期之间的天数差
 * @param startDate 开始日期
 * @param endDate 结束日期，默认为当前日期
 * @returns 天数差
 */
export const calculateDaysDiff = (startDate: Date | string, endDate: Date | string = new Date()): number => {
  if (!startDate) return 0;
  
  const start = dayjs(startDate);
  const end = dayjs(endDate);
  
  return Math.abs(end.diff(start, 'day'));
};

/**
 * 计算孕周和天数
 * @param lastMenstrualPeriod 末次月经日期
 * @returns 包含周数和天数的对象
 */
export const calculatePregnancyWeeks = (lastMenstrualPeriod: string): { weeks: number; days: number } => {
  if (!lastMenstrualPeriod) return { weeks: 0, days: 0 };
  
  const lmpDate = dayjs(lastMenstrualPeriod);
  const today = dayjs();
  const diffDays = today.diff(lmpDate, 'day');
  
  return {
    weeks: Math.floor(diffDays / 7),
    days: diffDays % 7
  };
};

/**
 * 计算预产期（末次月经+280天）
 * @param lastMenstrualPeriod 末次月经日期
 * @returns 预产期日期字符串
 */
export const calculateDueDate = (lastMenstrualPeriod: string): string => {
  if (!lastMenstrualPeriod) return '';
  
  return dayjs(lastMenstrualPeriod).add(280, 'day').format('YYYY-MM-DD');
};

/**
 * 计算宝宝月龄
 * @param birthDate 出生日期
 * @returns 包含月数和天数的对象
 */
export const calculateBabyAge = (birthDate: string): { months: number; days: number } => {
  if (!birthDate) return { months: 0, days: 0 };
  
  const birth = dayjs(birthDate);
  const today = dayjs();
  const diffDays = today.diff(birth, 'day');
  
  return {
    months: Math.floor(diffDays / 30),
    days: diffDays % 30
  };
};

/**
 * 获取宝宝年龄文本描述
 * @param birthDate 出生日期
 * @returns 年龄文本
 */
export const getBabyAgeText = (birthDate: string): string => {
  if (!birthDate) return '';
  
  const { months, days } = calculateBabyAge(birthDate);
  
  if (months === 0) {
    return `${days}天`;
  } else {
    return `${months}个月${days}天`;
  }
};

/**
 * 计算进度百分比
 * @param current 当前值
 * @param total 总值
 * @returns 百分比值（0-100）
 */
export const calculateProgress = (current: number, total: number): number => {
  if (total <= 0) return 0;
  return Math.min(Math.round((current / total) * 100), 100);
}; 